package com.sry.blog.utils;


import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {

    static int MAXSIZE = 62;

    public static String setSalt(int length) {
        char arr[] = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
                't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer salt = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            salt.append(arr[random.nextInt(MAXSIZE)]);
        }
        return salt.toString();
    }

    public static String setPassword(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        password += salt;
        byte[] digest = null;
        MessageDigest md5 = MessageDigest.getInstance("md5");
        digest = md5.digest(password.getBytes("utf-8"));
        return new BigInteger(1, digest).toString(16);
    }

}
